package com.kclm.xsap.web.controller;

import com.kclm.xsap.dao.LoginMapper;
import com.kclm.xsap.dto.EmployeeDTO;
import com.kclm.xsap.dto.UserDTO;
import com.kclm.xsap.entity.Employee;
import com.kclm.xsap.service.LoginService;
import com.kclm.xsap.vo.EmployeeVo;
import com.kclm.xsap.vo.UserVO;
import com.kclm.xsap.web.common.R;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * @Author : lvhx
 * @Date: 2025/6/13 15:57
 * @Description:
 * get   user/getUserInfo?id=1
 * post  user/updateUser
 * restful 风格的请求  无服务器的资源取名 user  product  settings
 *    get     /user
 *    post    /user
 *    put     /user/id
 *    delete  /user/1
 */
@RestController
@RequestMapping("/user")
@Slf4j  //localhost:8080/user/login
public class LoginController {
    private LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }
    //前端发发送过来的数据格式是json
    @PostMapping("login")
    public  R  login(@RequestBody EmployeeVo employeeVO, HttpSession session) {
        log.info("==>登录的信息为:{}",employeeVO);
        //服务器端生成的验证码
       String code = (String) session.getAttribute("verifyCode");
       log.info("服务器端的验证码:{}",code);
       //验证码的校验
        if(code==null){
            log.warn("服务端验证码为空");
            return R.error("验证码未生成");
        }
        if(!employeeVO.getCaptcha().equalsIgnoreCase(code)){
            log.warn("验证码输入错误：实际为：{},预期为：{}",employeeVO.getCaptcha(),code);
            return R.error("验证码输入错误");
        }
        try{
            //调用登录业务
            EmployeeDTO employeeDTO = loginService.login(employeeVO);
            if(employeeDTO==null){
                return R.error("用户名或者密码错误");
            }
            return  R.success(employeeDTO);
        }catch (Exception e){
            return  R.error("登录失败！");

        }

    }
    //根据用户的id查询用户的信息
    @GetMapping("/{id}")
    public  R  findById(@PathVariable("id") Integer id) {
        log.info("用户的id为:{}",id);
        //交给业务层  处理用户查询的操作
       try{
           UserDTO userDTO = loginService.findById(id);
           if(userDTO!=null){
               return R.success(userDTO);
           }else{
               return  R.error("id为"+id+"的用户不存在");
           }
       }catch (Exception e){
           return R.error("根据用户id查询失败");
       }
    }
    @Value("${file.upload_dir}")
    private  String  uploadDir;
   @PutMapping("/")
    public  R save(@RequestParam("file") MultipartFile file, UserVO userVO){
       log.info("用户信息:{}",userVO);
       try{
           String filename = file.getOriginalFilename();
           log.info("上传文件的名字:{}",filename);
           String ext = "";//获取文件扩展名
           int dotIndex = filename.lastIndexOf(".");
           if(dotIndex>0&&dotIndex<filename.length()-1){
               ext = filename.substring(dotIndex);
           }
           log.info("文件扩展名:{}",ext);
           //对文件名做处理
           String  randomFileName  = UUID.randomUUID().toString().replace("-","")+ext;
           log.info("生成的文件名：{}",randomFileName);
           //文件类型的校验
           //文件的保存路径
           Path uploadPath = Paths.get(uploadDir);
           if(!Files.exists(uploadPath)){
               Files.createDirectories(uploadPath);
           }
           // 文件的目标路径
           Path targetPath = uploadPath.resolve(randomFileName);
           Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

           //用户信息修改
           userVO.setAvatarUrl(randomFileName);
           log.info("用户添加了头像:{}",userVO);
           if(loginService.update(userVO)>0){
               return  R.success(userVO);
           }else {
               return  R.error("修改用信息失败");
           }

       }catch (Exception e){
           return  R.error("修改异常");
       }

   }

}
